package com.ghy.component;

import com.ghy.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.ghy.result.Result;
import com.ghy.result.ResultCode;

/**
 * @author GaoHeYang
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.ghy"})
public class ExceptionAdvice {
    @ExceptionHandler(ServiceException.class)
    public Object serviceException(ServiceException e){
        log.error("业务异常："+e.getMessage());
        return new Result<>(ResultCode.FAILED, e.getMessage());
    }
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Object methodArgumentNotValidException(Exception e) {
        //获取Banding和Result
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }else {
            bindingResult = ((BindException) e).getBindingResult();
        }
        //获取BindingResult中所有属性错误信息集合中的第一个属性错误
        FieldError firstFieldError = bindingResult.getFieldErrors().get(0);

        // 异常信息："xxx实例的xxx属性校验失败：xxx异常信息"
        String message = String.format("%s实例的%s属性校验失败：%s",
                firstFieldError.getObjectName(),
                firstFieldError.getField(),
                firstFieldError.getDefaultMessage());
        //记录目志
        log.error(message) ;
        //响应
        return new Result<>(ResultCode.VALIDATE_FAILED, message);

    }
    @ExceptionHandler(Exception.class)
    public Object exception(Exception e) {
        log.error("其他异常："+e.getMessage());
        return new Result<>(ResultCode.FAILED, e.getMessage());
    }

}
